import { InjectionKey } from "vue";
import { createStore, Store } from "vuex"
import setting from "../utils/setting";
import todos, { TodoState } from "./modules/todos"

//1创建一个InjectionKey
export const key:InjectionKey<Store<State>> = Symbol();

export type State = {
    tagsList:string[] | any[],
    collapse:boolean,
    userInfo:object | undefined,
    token:string | null,
    count:number,
    setting:object,
    todos?:TodoState   //此处写todos，是为了防止createStore提示报错
}

export default createStore({
    state:():State => ({
        count:2,
        tagsList: [],
        collapse: false,
        userInfo: localStorage.getItem("bussines_info") ? JSON.parse(localStorage.getItem("bussines_info") as string) : undefined,
        token: localStorage.getItem("bussines_token"),
        setting
    }),
    mutations:{
        add(state){
            state.count++;
        },
        delTagsItem(state, data) {
            state
                .tagsList
                .splice(data.index, 1);
        },
        setTagsItem(state, data) {
            state
                .tagsList
                .push(data)
        },
        clearTags(state) {
            state.tagsList = []
        },
        closeTagsOther(state, data) {
            state.tagsList = data;
        },
        closeCurrentTag(state, data) {
            for (let i = 0, len = state.tagsList.length; i < len; i++) {
                const item:any = state.tagsList[i];
                if (item.path === data.$route.fullPath) {
                    if (i < len - 1) {
                        data
                            .$router
                            .push(state.tagsList[i + 1].path);
                    } else if (i > 0) {
                        data
                            .$router
                            .push(state.tagsList[i - 1].path);
                    } else {
                        data
                            .$router
                            .push("/");
                    }
                    state
                        .tagsList
                        .splice(i, 1);
                    break;
                }
            }
        },
        // 侧边栏折叠
        hadndleCollapse(state, data) {
            state.collapse = data;
        },
        updateToken(state, data) {
            // 更新token信息
            state.token = data.access_token;
            state.userInfo = data.consumerDto;
        }
    },
    modules:{
        todos
    }
});